#!/usr/bin/env perl
use warnings;
use strict;
use Getopt::Long;
use FindBin qw($RealBin);
use lib "$RealBin/../lib";

## This program is Copyright (C) 2010-20, Felix Krueger <felix.krueger@babraham.ac.uk>.
## Thanks to Phil Ewels <phil.ewels@scilifelab.se> (who wrote a first version of this
## script in 2013 or so when it was still 'legal' to use Highcharts.js (or maybe it 
## never was?....))

## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.

## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details. 

## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
my $bismark_version = '0.22.4';

# Last modified 09 11 2020

my ($report_basename,$page_title,$verbose) = process_commandline();

sub process_commandline{
    my $help;
    my $version;
    my $title;
    my $manual_output_file;
    
    my $command_line = GetOptions ( 'help|man'              => \$help,
									'o|basename=s'          => \$manual_output_file,
									'title=s'               => \$title,
									'version'               => \$version,
									'verbose'               => \$verbose,
						);
    
    ### EXIT ON ERROR if there were errors with any of the supplied options
    unless ($command_line){
		die "Please respecify command line options\n";
    }
    
    ### HELPFILE
    if ($help){
		print_helpfile();
		exit;
    }
 
    if ($version){
		print << "VERSION";
	

                             Bismark HTML Summary Report
                                 powered by Plot.ly

                           bismark2summary version: $bismark_version
                          Copyright 2010-20 Felix Krueger
                               Babraham Bioinformatics
                 www.bioinformatics.babraham.ac.uk/projects/bismark/
                      https://github.com/FelixKrueger/Bismark



VERSION
		    exit;
    }
    unless (defined $title){
		$title = '';
    }
    unless (defined $manual_output_file){
		$manual_output_file = '';
    }
    
    return ($manual_output_file,$title,$verbose); 

}

sub print_helpfile{
	  print <<EOF

	  SYNOPSIS:

	  This script uses Bismark report files of several samples in a run folder to generate a graphical summary HTML report as well as
	  a whopping big table (tab delimited text) with all relevant alignment and methylation statistics which may be used for graphing
	  purposes in R, Excel or the like. Unless specific BAM files are specified, bismark2summary first identifies Bismark BAM files in
	  a folder (they need to use the Bismark naming conventions) and then automatically detects Bismark alignment, deduplication or
	  methylation extractor (splitting) reports based on the input file basename. If splitting reports are found they overwrite the
	  methylation statistics of the initial alignment report.

      Files with absulutely no methylation calls in any context are excluded from the HTML graphs (as they break the rendering with 
      plot.ly. Such files and their values are reported in the file "bismark_summary_report.txt".

	  USAGE: bismark2summary [options] [<BAM file(s)>]

	  ARGUMENTS:

	  BAM file(s)                 Optional. If no BAM files are specified explicitly the current working directory is scanned for 
								  Bismark alignment files and their associated reports. 

	  OPTIONS:

	  -o/--basename <filename>    Basename of the output file (optional). Generate a text file with all relevant extracted values
								  ('basename.txt') as well as an HTML report ('basename.html'). If not specified explicitly, the
								  the basename is 'bismark_summary_report'.

	  --title <string>            Optional HTML report title; use --title "speech marks for text with spaces". Default: 
								  'Bismark Summary Report'. 			      


	  --version                   Displays version information and exits.
					  
	  --help                      Displays this help message and exits.


													Script last modified: 09 November 2020

EOF
		;
  exit 1;
}


my $plotly_code  = read_report_template('plot.ly');
my $bismark_logo = read_report_template('bismark.logo');
my $bioinf_logo  = read_report_template('bioinf.logo');


#warn "Got Plot.ly:\n$plotly_code\n\n"; sleep(1);
#warn "Got Bismark logo:\n$bismark_logo\n\n"; sleep(1);
#warn "Got Bioinf:\n$bioinf_logo\n\n"; sleep(1);

sub read_report_template{
    my $template = shift;
    my $doc;
    warn "Attempting to open file from: $RealBin/$template\n" if ($verbose);
    open (DOC,"$RealBin/plotly/$template") or die "Failed to find file $template: $!";
    while(<DOC>){
	chomp;
	$_ =~ s/\r//g;
	$doc .= $_."\n";
    }
    
    close DOC or die $!;
    return $doc;
}


### AUTO-DETECTING BISMARK BAM FILES
my @bam_files = @ARGV; # user supplied BAM files
unless (@bam_files){
    my @detected_files;

    # If not user supplied we try to find BAM files automatically. Note that this will go horribly wrong if there were BAM files from another aligner in the same folder as well

    @detected_files = <*bismark_bt2.bam>; # SE Bowtie2
    if (@detected_files){
		warn "Found Bismark/Bowtie2 single-end files\n";
		push (@bam_files,@detected_files); # appending found files
		@detected_files = ();
    }
    else{
		warn "No Bismark/Bowtie2 single-end BAM files detected\n";
    }

    @detected_files = <*bismark_bt2_pe.bam>; # PE Bowtie2
    if (@detected_files){
		warn "Found Bismark/Bowtie2 paired-end files\n";
		push (@bam_files,@detected_files); # appending found files
		@detected_files = ();
    }
    else{
		warn "No Bismark/Bowtie2 paired-end BAM files detected\n"; 
    }
    
    @detected_files = <*bismark_hisat2.bam>; # SE HISAT2
    if (@detected_files){
		warn "Found Bismark/HISAT2 single-end files\n";
		push (@bam_files,@detected_files); # appending found files
		@detected_files = ();
    }
    else{
		warn "No Bismark/HISAT2 single-end BAM files detected\n";
    }	

    @detected_files = <*bismark_hisat2_pe.bam>; # PE HISAT2
    if (@detected_files){
		warn "Found Bismark/HISAT2 paired-end files\n";
		push (@bam_files,@detected_files); # appending found files
		@detected_files = ();
    }
    else{
		warn "No Bismark/HISAT2 paired-end BAM files detected\n\n"; 
    }
}

if(scalar @bam_files == 0){
    die("Error: No Bismark BAM files found to generate a Bismark project summary. Please respecify...\n\nUSAGE:\nbismark2summary (*.bam), or bismark2summary --help for more information");
}
else {
    warn("Generating Bismark summary report from ",scalar @bam_files," Bismark BAM file(s)...\n");
}

unless ($report_basename){
    $report_basename = 'bismark_summary_report';
}
unless ($page_title){
    $page_title = 'Bismark Summary Report';
}

my @categories_arr;
my @not_aligned_arr;
my @aligned_arr;
my @ambig_aligned_arr;
my @no_seq_arr;
my @dup_alignments_arr;
my @unique_alignments_arr;
my @meth_cpg_string_arr;
my @unmeth_cpg_string_arr;
my @meth_chg_string_arr;
my @unmeth_chg_string_arr;
my @meth_chh_string_arr;
my @unmeth_chh_string_arr;

my @summary_csv_fields = (
    'File',
    'Total Reads',
    'Aligned Reads',
    'Unaligned Reads',
    'Ambiguously Aligned Reads',
    'No Genomic Sequence',
    'Duplicate Reads (removed)',
    'Unique Reads (remaining)',
    'Total Cs',
    'Methylated CpGs',
    'Unmethylated CpGs',
    'Methylated chgs',
    'Unmethylated chgs',
    'Methylated CHHs',
    'Unmethylated CHHs'
);

my $summary_csv = join("\t",@summary_csv_fields)."\n";
my $num_samples = scalar @bam_files;
for my $bam (@bam_files){

    # Set up variables
    my $base = substr($bam, 0, -4); # removes .bam from the end
    my $total_reads = '';
    my $aligned_reads = '';
    my $unaligned = '';
    my $ambig_reads = '';
    my $no_seq_reads = '';
    my $dup_reads = '';
    my $unique_reads = '';
    my $total_c = '';
    my $meth_cpg = '';
    my $unmeth_cpg = '';
    my $meth_chg = '';
    my $unmeth_chg = '';
    my $meth_chh = '';
    my $unmeth_chh = '';
    
    # Bismark report
    my $bm_report;
    my $paired_end = 0;

    if ($base =~ /_pe$/){
    	$base  =~ s/_pe$//;
    	$bm_report = $base."_PE_report.txt";
    	$paired_end = 1;
    } else {
        $bm_report = $base."_SE_report.txt";
    }

    ### Bismark reports are mandatory, deduplication or methylation extractor reports are optional
    if (-e $bm_report){ # 
	warn ">> Reading from Bismark report: $bm_report\n";
    } 
    else {
    	die "Could not find Bismark report ($bm_report) to open\n";
    }
    
    open (BISMARK_REPORT, "<", $bm_report) or warn "Warning! Couldn't read from Bismark report $bm_report: $!\n\n";	
    while(<BISMARK_REPORT>){
	chomp;
	if ($paired_end){
	    $total_reads = $1 if (/^Sequence pairs analysed in total:\s+(\d+)$/);
	    $unaligned = $1 if (/^Sequence pairs with no alignments under any condition:\s+(\d+)$/);
	    $ambig_reads = $1 if (/^Sequence pairs did not map uniquely:\s+(\d+)$/);
	    $no_seq_reads = $1 if (/^Sequence pairs which were discarded because genomic sequence could not be extracted:\s+(\d+)$/);
	    $aligned_reads = $1 if (/^Number of paired-end alignments with a unique best hit:\s+(\d+)$/);
	}
	else{
	    $total_reads = $1 if (/^Sequences analysed in total:\s+(\d+)$/);
	    $unaligned = $1 if (/^Sequences with no alignments under any condition:\s+(\d+)$/);
	    $ambig_reads = $1 if (/^Sequences did not map uniquely:\s+(\d+)$/);
	    $no_seq_reads = $1 if (/^Sequences which were discarded because genomic sequence could not be extracted:\s+(\d+)$/);
	    $aligned_reads = $1 if (/^Number of alignments with a unique best hit from the different alignments:\s+(\d+)$/);
	}

	$total_c = $1 if(/^Total number of C's analysed:\s+(\d+)$/);
	$meth_cpg = $1 if(/^Total methylated C's in CpG context:\s+(\d+)/);
	$meth_chg = $1 if(/^Total methylated C's in CHG context:\s+(\d+)/);
	$meth_chh = $1 if(/^Total methylated C's in CHH context:\s+(\d+)/);
	$unmeth_cpg = $1 if(/^Total unmethylated C's in CpG context:\s+(\d+)/);
	$unmeth_chg = $1 if(/^Total unmethylated C's in CHG context:\s+(\d+)/);
	$unmeth_chh = $1 if(/^Total unmethylated C's in CHH context:\s+(\d+)/);
	
    }
    # warn "'$total_c'\t'$meth_cpg'\t'$meth_chg'\t'$meth_chh'\t'$unmeth_cpg'\t'$unmeth_chg'\t'$unmeth_chh'\n";	
    close(BISMARK_REPORT) or warn "Failed to close filehandle BISMARK REPORT: $!\n\n";
    
    ### Deduplication report (optional)
    my $dedup;
    if ($paired_end){
        $dedup = $base."_pe.deduplication_report.txt";
    } 
    else {
        $dedup = $base.".deduplication_report.txt";
    }

    if(-e $dedup){
        open(DEDUP, "<", $dedup) or warn "Warning! Couldn't open deduplication report $dedup: $!\n\n";
		while(<DEDUP>){
			chomp;
			if(/^Total number of alignments analysed in .+:\s+(\d+)$/){
                $aligned_reads = $1;
                # warn "Setting aligned reads to $aligned_reads\n";
			}
			if(/^Total number duplicated alignments removed:\s+(\d+)/){
                $dup_reads = $1;
                # warn "Setting deduplicated reads to $dup_reads\n";
			}
			if(/^Total count of deduplicated leftover sequences:\s+(\d+)/){
                $unique_reads = $1;
                # warn "Setting unique reads to $unique_reads\n";
			}

		}
		close(DEDUP);
    }
    else{
	    warn "No deduplication report present, skipping...\n";
    }
    
    ### Methylation Extraction report (optional)
    my $meth_extract;
    if ($paired_end){
         if(-e $dedup){ # deduplication report is present
            $meth_extract = $base."_pe.deduplicated_splitting_report.txt";
         }
         else{ #  no deduplication present, e.g. RRBS
            $meth_extract = $base."_pe_splitting_report.txt";
         }
    }
    else{
        if(-e $dedup){ # deduplication report is present
            $meth_extract = $base.".deduplicated_splitting_report.txt";
        }
        else{ #  no deduplication present, e.g. RRBS
            $meth_extract = $base."_splitting_report.txt";
        }
    }
    
    if(-e $meth_extract){
        open(METHEXTR, "<", $meth_extract) or warn "Warning! Couldn't open methylation extractor report $meth_extract: $!\n";
		while(<METHEXTR>){
			chomp;
			$total_c = $1 if(/^Total number of C's analysed:\s+(\d+)$/);
			$meth_cpg = $1 if(/^Total methylated C's in CpG context:\s+(\d+)/);
			$meth_chg = $1 if(/^Total methylated C's in CHG context:\s+(\d+)/);
			$meth_chh = $1 if(/^Total methylated C's in CHH context:\s+(\d+)/);
			$unmeth_cpg = $1 if(/^Total C to T conversions in CpG context:\s+(\d+)/);
			$unmeth_chg = $1 if(/^Total C to T conversions in CHG context:\s+(\d+)/);
			$unmeth_chh = $1 if(/^Total C to T conversions in CHH context:\s+(\d+)/);
		}
		close(METHEXTR);
    }
    else{
		warn "No methylation extractor report present, skipping...\n";
    }

    my @csvrow = (
        $bam,
        $total_reads,
        $aligned_reads,
        $unaligned,
        $ambig_reads,
        $no_seq_reads,
        $dup_reads,
        $unique_reads,
        $total_c,
        $meth_cpg,
        $unmeth_cpg,
        $meth_chg,
        $unmeth_chg,
        $meth_chh,
        $unmeth_chh
    );
    $summary_csv .= join("\t", @csvrow)."\n"; # appending a new line every time
  
    my $name = $bam;
    $name =~ s/_bismark.bam$//;
    $name =~ s/\.fq\.gz$//;
    $name =~ s/_trimmed$//;
    $name =~ s/_[12]$//;

    $unaligned = 0      if $unaligned eq '';
    $ambig_reads = 0    if $ambig_reads eq '';
    $no_seq_reads = 0   if $no_seq_reads eq '';
    # if no deduplication has been performed we need to treat unique reads slighlty differently
    if ($dup_reads ne ''){
		$aligned_reads = "";
    }
    $meth_cpg = 0       if $meth_cpg eq '';
    $unmeth_cpg = 0     if $unmeth_cpg eq '';
    $meth_chg = 0       if $meth_chg eq '';
    $unmeth_chg = 0     if $unmeth_chg eq '';
    $meth_chh = 0       if $meth_chh eq '';
    $unmeth_chh = 0     if $unmeth_chh eq '';
    

    # Samples with 0 calls in different context result in completely non-rendered plots. We therefore exclude these samples
    # from the plotting. Their values are still present in the Textfile summary though
    if ($meth_cpg == 0 and $unmeth_cpg == 0){
        warn "Excluding sample >$name< for plotting as there were no calls in CpG context\n";
        next;
    }  
     if ($meth_chg == 0 and $unmeth_chg == 0){
        warn "Excluding sample >$name< for plotting as there were no calls in CHG context\n";
        next;
    }  
     if ($meth_chh == 0 and $unmeth_chh == 0){
        warn "Excluding sample >$name< for plotting as there were no calls in CHH context\n";
        next;
    }  

    push(@categories_arr,          "'$name'");
    push(@aligned_arr,             $aligned_reads);
    push(@not_aligned_arr,         $unaligned);
    push(@ambig_aligned_arr,       $ambig_reads);
    push(@no_seq_arr,              $no_seq_reads);

    push(@dup_alignments_arr,      $dup_reads);
    push(@unique_alignments_arr,   $unique_reads);
    push(@meth_cpg_string_arr,     $meth_cpg);
    push(@unmeth_cpg_string_arr,   $unmeth_cpg);
    push(@meth_chg_string_arr,     $meth_chg);
    push(@unmeth_chg_string_arr,   $unmeth_chg);
    push(@meth_chh_string_arr,     $meth_chh);
    push(@unmeth_chh_string_arr,   $unmeth_chh);
    
    # warn "'$name'\t$unaligned\t$ambig_reads\t$no_seq_reads\t$dup_reads\t$unique_reads\t$meth_cpg\t$unmeth_cpg\t$meth_chg\t$unmeth_chg\t$meth_chh\t$unmeth_chh\n";sleep(1);
}

my $categories = join(",", @categories_arr);
my $aligned = join(",", @aligned_arr);
my $not_aligned = join(",", @not_aligned_arr);
my $ambig_aligned = join(",", @ambig_aligned_arr);
my $no_seq = join(",", @no_seq_arr);
my $dup_alignments = join(",", @dup_alignments_arr);
my $unique_alignments = join(",", @unique_alignments_arr);

my $meth_cpg_string   = join(",", @meth_cpg_string_arr);
my $unmeth_cpg_string = join(",", @unmeth_cpg_string_arr);
my $meth_chg_string   = join(",", @meth_chg_string_arr);
my $unmeth_chg_string = join(",", @unmeth_chg_string_arr);
my $meth_chh_string   = join(",", @meth_chh_string_arr);
my $unmeth_chh_string = join(",", @unmeth_chh_string_arr);



# Write the numeric data to a summary file
my $summary_fn = $report_basename.".txt";
open(SUMMARY_CSV, ">", $summary_fn) or die("Can't open $summary_fn: $!\n");
print SUMMARY_CSV $summary_csv;
close(SUMMARY_CSV);





# Write a nice HTML summary report
my $report_timestamp = localtime;
my $html_report = <<'HTMLTEMPLATESTRING';
<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="content-type" content="text/html; charset=UTF-8">
	<title>Bismark Project Summary Report - {{page_title}}</title>
	<style type="text/css">
		body {
			font-family: Arial, sans-serif;
			font-size:14px;
			padding:0 20px 20px;
		}
		.container {
			margin:0 auto;
		}
		.header h1,
		.header img {
			float:left;
		}
		.header h1 {
			margin: 20px 0 10px;
		}
		.header img {
			padding: 0 20px 20px 0;
		}
		.subtitle {
			margin-top:120px;
			float:right;
			text-align:right;
		}
		.header_subtitle h3,
		.header_subtitle p {
			margin:0;
		}
		h1 {
			font-size: 3.2em;
		}
		h2 {
			font-size:2.2em;
		}
		h3 {
			font-size:1.4em;
		}
		h2, h3, hr {
			clear:both;
		}
		hr {
			border-top:1px solid #CCC;
			border-bottom:1px solid #F3F3F3;
			border-left:0;
			border-right:0;
			height:0;
		}
		.plot {
			width:100%;
			margin-bottom:0px;
            height: 350px;
		}
        .plot_meth{
            width:100%;
            margin-bottom:0px;
            margin-top: 0px;
            height:200px;
        }
		footer {
			color:#999;
		}
		footer a {
			color:#999;
		}
        .switch_group {
			margin-left:20px;
			display:inline-block;
			line-height: 1em;
		}
		.switch_group button {
			vertical-align:top;
			border: 1px solid #2f7ed8;
			border-left:0;
			background-color: #2f7ed8;
			color:#FFFFFF;
			padding: 8px;
			outline: none;
			cursor: pointer;
			-webkit-transition: background-color 150ms ease-in-out;
			-moz-transition: background-color 150ms ease-in-out;
			-o-transition: background-color 150ms ease-in-out;
			-ms-transition: background-color 150ms ease-in-out;
			transition: background-color 150ms ease-in-out;
		}
		.switch_group button:first-child {
			border-left: 1px solid #2f7ed8;
		}
		.switch_group button.active {
			background-color: #2f7ed8;
			color:#FFFFFF;
		}
	</style>

	<!-- Plotly.js -->
	{{plotly_goes_here}}
 	This will need to be replaced by the plot.ly library itself
 	{{plotly_goes_here}}
	
</head>
<body>


<div class="container">
	<div class="header">
		{{bismark_logo_goes_here}}
		<h1>Bismark Project Overall Summary</h1>
		<div class="subtitle">
			<h3>{{page_title}}</h3>
			<p>Report generated on {{report_timestamp}}</p>
		</div>
	</div>
	<hr>
	<h2>
		Alignment Statistics
		<div class="switch_group">
			<!-- <button id="version1">Number of Reads</button> <button id="version2">Percentages</button></div><div id="myData" style="width: 100%;"></div> -->
	</h2>
		
	<div id="alignmentPercentage" class="plot"><!-- Plotly chart will be drawn inside this DIV --></div>
	<div id="alignmentNumbers" class="plot"><!-- Plotly chart will be drawn inside this DIV --></div>
    <hr>
	<h2>
		Cytosine Methylation
	</h2>
        <div id="methylation_context_CpG" class="plot_meth"></div> 
        <div id="methylation_context_CHG" class="plot_meth"></div>
        <div id="methylation_context_CHH" class="plot_meth"></div>
	<hr>
	
	<!-- ### PLOT.LY CODE ##################################################################################################### -->

    <!-- ### ALIGNMENT SECTION -->

	<script>
		var alignment_plot_colors = ['#f28f43', '#0d233a', '#492970', '#2f7ed8', '#8bbc21'];
		var alignment_plot_colors2 = ['#01665e','#f28f43', '#0d233a', '#492970', '#2f7ed8', '#8bbc21'];	
		var meth_plot_colors = ['#0d233a', '#2f7ed8', '#8bbc21', '#1aadce', '#910000', '#492970'];
		var stacksDivPercentage = document.getElementById("alignmentPercentage");
        var stacksDivNumbers = document.getElementById("alignmentNumbers");
		var num_samples = {{num_samples}};
		
		var traces1 = [
			
			{x: [{{x_values_alignment}}], y: [{{no_seq}}],
				fill: 'tonexty',
				text: [{{filenames_replace}}],
				hovertext: [{{filenames_replace}}],
				name:'No Genomic Sequence',
				fillcolor: '#f28f43',
                line:{
                    color: '#f28f43',
                    width: 1,
                },
                marker:{
                    symbol: 'circle-dot',
                    size: 7,
                    line:{
                        color: 'black',
                        width:1,
                    },
                },
			},
			<!-- Either deduplicated unique reads or Raw unique reads here (e.g. for RRBS) -->
			{{raw_aligned_reads_section}}
			{x: [{{x_values_alignment}}], y: [{{aligned_seq}}],
				fill: 'tozeroy',
				text: [{{filenames_replace}}],
				hovertext: [{{filenames_replace}}],
				name:'Raw Aligned Reads',
				fillcolor: '#01665e',
				visible: true,
                line:{
                    color: '#01665e',
                    width: 1,
                },
                marker:{
                    symbol: 'circle-dot',
                    size: 7,
                    line:{
                        color: 'black',
                        width:1,
                    },
                },
			},
			{{raw_aligned_reads_section}}
			{{deduplicated_unique_reads_section}}
			{x: [{{x_values_alignment}}], y: [{{unique_alignments}}],
				name:'Deduplicated Unique Alignments',
				text: [{{filenames_replace}}],
				hovertext: [{{filenames_replace}}],
				fill: 'tonexty', 
				fillcolor: '#8bbc21',
                line:{
                    color: '#8bbc21',
                    width: 1,
                },
                marker:{
                    symbol: 'circle-dot',
                    size: 7,
                    line:{
                        color: 'black',
                        width:1,
                    },
                },
			},
			{{deduplicated_unique_reads_section}}
			{{duplicated_reads_section}}
			{x: [{{x_values_alignment}}], y: [{{dup_alignments}}],
				name:'Duplicate Alignments',
				text: [{{filenames_replace}}],
				hovertext: [{{filenames_replace}}],
				fill: 'tonexty', 
				fillcolor: '#2f7ed8',
                line:{
                    color: '#2f7ed8',
                    width: 1,
                },
                marker:{
                    symbol: 'circle-dot',
                    size: 7,
                    line:{
                        color: 'black',
                        width:1,
                    },
                },
			},
			{{duplicated_reads_section}}
			{x: [{{x_values_alignment}}], y: [{{ambig_aligned}}],
				name:'Aligned Ambiguously',
				text: [{{filenames_replace}}],
				hovertext: [{{filenames_replace}}],
				fill: 'tonexty',
				fillcolor: '#492970',
                line:{
                    color: '#492970',
                    width: 1,
                },
                marker:{
                    symbol: 'circle-dot',
                    size: 7,
                    line:{
                        color: 'black',
                        width:1,
                    },
                },
			},
			{x: [{{x_values_alignment}}], y: [{{not_aligned}}],
				fill: 'tonexty',
				name:'Did Not Align',
				text: [{{filenames_replace}}],
				hovertext: [{{filenames_replace}}],
				fillcolor: '#0d233a',
                line:{
                    color: '#0d233a',
                    width: 1,
                },
                marker:{
                    symbol: 'circle-dot',
                    size: 7,
                    line:{
                        color: 'black',
                        width:1,
                    },
                },
			},
		];
	
		<!-- Percentage Plots -->
        var traces2 = [
            
			
			{x: [{{x_values_alignment}}], y: [{{p_no_seq_replace}}],
				text: [{{filenames_replace}}],
				hovertext: [{{filenames_replace}}],
                fill: 'tozeroy',
                name:'No Genomic Sequence',
				hoveron: 'points+fills',
                fillcolor: '#f28f43',
                line:{
                    color: '#f28f43',
                    width: 1,
                },
                marker:{
                    symbol: 'circle-dot',
                    size: 7,
                    line:{
                        color: 'black',
                        width:1,
                    },
                },
            },
			<!-- Either deduplicated unique reads or Raw unique reads here (e.g. for RRBS) -->
			{{deduplicated_unique_reads_percentage_section}}
			{x: [{{x_values_alignment}}], y: [{{p_deduplicated_unique_alignments}}],
				text: [{{filenames_replace}}],
				hovertext: [{{filenames_replace}}],
				hoveron: 'points+fills',
				name:'Deduplicated Unique Alignments',
				fill: 'tonexty', 
				fillcolor: '#8bbc21',
                line:{
                    color: '#8bbc21',
                    width: 1,
                },
                marker:{
                    symbol: 'circle-dot',
                    size: 7,
                    line:{
                        color: 'black',
                        width:1,
                    },
                },
			},
			{{deduplicated_unique_reads_percentage_section}}
			{{duplicated_reads_percentage_section}}
			{x: [{{x_values_alignment}}], y: [{{p_duplicated_alignments}}],
				text: [{{filenames_replace}}],
				hovertext: [{{filenames_replace}}],
				name:'Duplicate Alignments', 
				hoveron: 'points+fills',
				fill: 'tonexty', 
				fillcolor: '#2f7ed8',
                line:{
                    color: '#2f7ed8',
                    width: 1,
                },
                marker:{
                    symbol: 'circle-dot',
                    size: 7,
                    line:{
                        color: 'black',
                        width:1,
                    },
                },
			},
			{{duplicated_reads_percentage_section}}
			{{raw_unique_reads_percentage_section}}
			{x: [{{x_values_alignment}}], y: [{{p_aligned_replace}}],
				text: [{{filenames_replace}}],
				hovertext: [{{filenames_replace}}],
				hoveron: 'points+fills',
                fill: 'tonexty',
                name:'Raw Aligned Reads',
                fillcolor: '#01665e',
                visible: true,
                line:{
                    color: '#01665e',
                    width: 1,
                },
                marker:{
                    symbol: 'circle-dot',
                    size: 7,
                    line:{
                        color: 'black',
                        width:1,
                    },
                },
            },
			{{raw_unique_reads_percentage_section}}
			
			{x: [{{x_values_alignment}}], y: [{{p_ambig_replace}}],
				hovertext: [{{filenames_replace}}],
				text: [{{filenames_replace}}],
                name:'Aligned Ambiguously',
				hoveron: 'points+fills',
                fill: 'tonexty',
                fillcolor: '#492970',
                line:{
                    color: '#492970',
                    width: 1,
                },
                marker:{
                    symbol: 'circle-dot',
                    size: 7,
                    line:{
                        color: 'black',
                        width:1,
                    },
                },
            },			
            {x: [{{x_values_alignment}}], y: [{{p_unal_replace}}],
				hovertext: [{{filenames_replace}}],
				text: [{{filenames_replace}}],
				hoveron: 'points+fills',
                fill: 'tonexty',
                name:'Did Not Align',
                fillcolor: '#0d233a',
                line:{
                    color: '#0d233a',
                    width: 1,
                },
                marker:{
                    symbol: 'circle-dot',
                    size: 7,
                    line:{
                        color: 'black',
                        width:1,
                    },
                },
            },

        ];

		function stackedArea(traces) {
			var i, j;
			for(i=0; i<traces.length; i++) {
				traces[i].text = [];
				traces[i].hoverinfo = 'all';
				for(j=0; j<(traces[i]['y'].length); j++) {
					traces[i].text.push(traces[i]['y'][j].toFixed(0)+" "+ traces[i].name);
				}
			}
			for(i=1; i<traces.length; i++) {
				for(j=0; j<(Math.min(traces[i]['y'].length, traces[i-1]['y'].length)); j++) {
					traces[i]['y'][j] += traces[i-1]['y'][j];
				}
			}
			return traces;
		}
		
		var layoutNumbers = {
		
			hoverlabel:{
				namelength: -1,
			},
			xaxis: {
				titlefont: {
					size: 14,
					color: '#4d759e',
				},
				showgrid: false,
                title: '<b>Sample [Hover to identify Sample and Numbers]</b>',
			},
			margin: {
                l: 50,
                r: 20,
                b: 40,
                t: 0, 
                pad: 0,           
            },
			yaxis: {
				title: '<b># Reads</b>',
				titlefont: {
					size: 14,
					color: '#4d759e',
				}
			},
			legend:{
				x: 0.4,
				y: 1.08,
				orientation: 'h',
			}				
		}
        var layoutPercentage = {
			hoverlabel:{
				namelength: -1,
			},
            xaxis: {
                titlefont: {
                    size: 14,
                    color: '#4d759e',
                },
                showgrid: false,
            },
             margin: {
                l: 50,
                r: 20,
                b: 40,
                t: 0,
                pad: 0,
            },
            yaxis: {
                title: '<b>% of all Reads</b>',
                titlefont: {
                    size: 14,
                    color: '#4d759e',
                },
				hoverformat: '.2f',
            },
            legend:{
                x: 0.4,
                y: 1.08,
                orientation: 'h',
            },
        };
	
		var optionsPercentage = {
			displaylogo: false,
			modeBarButtonsToRemove:
				['zoom2d', 
				'pan', 
				'pan2d',
				'resetScale2d',
				'hoverClosestCartesian',
				'hoverCompareCartesian',
				'toggleSpikelines']
			,
			toImageButtonOptions: {
				filename: 'Bismark Alignment Stats Summary',
				width: 1600,  <!-- width: stacksDivPercentage._fullLayout.width, height: stacksDivPercentage._fullLayout.height -->
				height: 400,
				format: 'png'
			}
		};
		
		var optionsNumbers = {
			displaylogo: false,
			modeBarButtonsToRemove:
				['zoom2d', 
				'pan', 
				'pan2d',
				'resetScale2d',
				'hoverClosestCartesian',
				'hoverCompareCartesian',
				'toggleSpikelines']
			,
			toImageButtonOptions: {
				filename: 'Bismark Alignment Stats Numbers',
				width: 1600,
				height: 400,
				format: 'png'
			}
		};
       
		Plotly.newPlot(stacksDivPercentage, stackedArea(traces2), layoutPercentage, optionsPercentage);
		
        Plotly.newPlot(stacksDivNumbers, stackedArea(traces1), layoutNumbers, optionsNumbers);
		     
			
	</script>

    <!-- ### METHYLATION CONTEXT -->

    <script>
        var alignment_plot_colors2 = ['#01665e','#f28f43', '#0d233a', '#492970', '#2f7ed8', '#8bbc21']; 
        var meth_plot_colors = ['#0d233a', '#2f7ed8', '#8bbc21', '#1aadce', '#910000', '#492970'];
        var methylationDiv_CpG = document.getElementById("methylation_context_CpG");

        var methylationDiv_CHG = document.getElementById("methylation_context_CHG");

        var methylationDiv_CHH = document.getElementById("methylation_context_CHH");

        var num_samples = {{num_samples}};
        
        <!-- CpG methylation calls -->
        var traces_m1 = [ 
            <!-- {x: [{{x_values_methylation}}], y: [{{meth_cpg_string}}], -->
            {x: [{{x_values_methylation}}], y: [{{p_CpG_m_replace}}], 
                fill: 'tozeroy',
                name:'Methylated CpG',
				text: [{{filenames_replace}}],
				hovertext: [{{filenames_replace}}],
                fillcolor: '#0d233a',
                visible: true,
                line:{
                    color: '#0d233a',
                    width: 1,
                },
                marker:{
                    symbol: 'circle-dot',
                    size: 7,
                    line:{
                        color: 'black',
                        width:1,
                    },
                },
            },
            <!-- {x: [{{x_values_methylation}}], y: [{{unmeth_cpg_string}}], -->
            {x: [{{x_values_methylation}}], y: [{{p_CpG_u_replace}}], 
                fill: 'tonexty',
                name:'Unmethylated CpG',
				text: [{{filenames_replace}}],
				hovertext: [{{filenames_replace}}],
                fillcolor: '#2f7ed8',
                line:{
                    color: '#2f7ed8',
                    width: 1,
                },
                marker:{
                    symbol: 'circle-dot',
                    size: 7,
                    line:{
                        color: 'black',
                        width:1,
                    },
                },
            },
        ];

        <!-- CHG methylation calls -->
        var traces_m2 = [ 
            <!-- {x: [{{x_values_methylation}}], y: [{{meth_chg_string}}], -->
            {x: [{{x_values_methylation}}], y: [{{p_CHG_m_replace}}], 
                fill: 'tozeroy',
				text: [{{filenames_replace}}],
				hovertext: [{{filenames_replace}}],
                name:'Methylated CHG',
                fillcolor: '#1aadce',
                visible: true,
                line:{
                    color: '#1aadce',
                    width: 1,
                },
                marker:{
                    symbol: 'circle-dot',
                    size: 7,
                    line:{
                        color: 'black',
                        width:1,
                    },
                },
            },
            <!-- {x: [{{x_values_methylation}}], y: [{{unmeth_chg_string}}], -->
            {x: [{{x_values_methylation}}], y: [{{p_CHG_u_replace}}], 
                fill: 'tonexty',
                name:'Unmethylated CHG',
				text: [{{filenames_replace}}],
				hovertext: [{{filenames_replace}}],
                fillcolor: '#8bbc21',
                line:{
                    color: '#8bbc21',
                    width: 1,
                },
                marker:{
                    symbol: 'circle-dot',
                    size: 7,
                    line:{
                        color: 'black',
                        width:1,
                    },
                },
            },
        ];

         <!-- CHH methylation calls -->
        var traces_m3 = [ 
            <!-- {x: [{{x_values_methylation}}], y: [{{meth_chh_string}}],  -->
                {x: [{{x_values_methylation}}], y: [{{p_CHH_m_replace}}], 
                fill: 'tozeroy',
				text: [{{filenames_replace}}],
				hovertext: [{{filenames_replace}}],
                line:{
                    color: '#492970',
                    width: 1,
                },
                marker:{
                    symbol: 'circle-dot',
                    size: 7,
                    line:{
                        color: 'black',
                        width:1,
                    },
                },
                name:'Methylated CHH',
                fillcolor: '#492970',
                visible: true,
            },
            <!-- {x: [{{x_values_methylation}}], y: [{{unmeth_chh_string}}],  -->
                {x: [{{x_values_methylation}}], y: [{{p_CHH_u_replace}}], 
                fill: 'tonexty',
				text: [{{filenames_replace}}],
				hovertext: [{{filenames_replace}}],
                line:{
                    color: '#910000',
                    width: 1,
                },
                marker:{
                    symbol: 'circle-dot',
                    size: 7,
                    line:{
                        color: 'black',
                        width:1,
                    },
                },
                name:'Unmethylated CHH',
                fillcolor: '#910000',
            },
        ];

        function stackedArea(traces) {
            var i, j;
            for(i=0; i<traces.length; i++) {
                traces[i].text = [];
                traces[i].hoverinfo = 'all';
                for(j=0; j<(traces[i]['y'].length); j++) {
                    traces[i].text.push(traces[i]['y'][j].toFixed(0)+" "+traces[i].name);
                }
            }
            for(i=1; i<traces.length; i++) {
                for(j=0; j<(Math.min(traces[i]['y'].length, traces[i-1]['y'].length)); j++) {
                    traces[i]['y'][j] += traces[i-1]['y'][j];
                }
            }
            return traces;
        }
        
        var layoutReads = {
			hoverlabel:{
				namelength: -1,
			},
            xaxis: {
                title: '<b>Sample [Hover to identify Sample and Numbers]</b>',
                titlefont: {
                    size: 14,
                    color: '#4d759e',
                }
                
            },
            yaxis: {
                title: '<b># Methylation Calls</b>',
                titlefont: {
                    size: 14,
                    color: '#4d759e',
                }
            },
            height: 400,
            legend:{
                x: 0.45,
                y: 1.1,
                orientation: 'h',
            }               
        }
        var layoutCpG = {
			hoverlabel:{
				namelength: -1,
			},
            <!--title: '<b>Sample [Hover to identify Sample and Numbers]</b>',-->
            yaxis: {
                title: '<b>% CpG Calls</b>',
                titlefont: {
                    size: 14,
                    color: '#4d759e',
                }
            },
            margin: {
                l: 50,
                r: 20,
                b: 20,
                t: 0,
                pad: 0,
            },
            legend:{
                x: 0.8,
                y: 0.9,
                orientation: 'h',
            }               
        }

         var layoutCHG = {
            <!--title: '<b>Sample [Hover to identify Sample and Numbers]</b>',-->
            hoverlabel:{
				namelength: -1,
			},
			yaxis: {
                title: '<b>% CHG Calls</b>',
                titlefont: {
                    size: 14,
                    color: '#4d759e',
                }
            },
            margin: {
                l: 50,
                r: 20,
                b: 20,
                t: 0,
                pad: 0,
            },
            legend:{
                x: 0.8,
                y: 0.9,
                orientation: 'h',
            }               
        }

         var layoutCHH = {
			hoverlabel:{
				namelength: -1,
			},
            <!--title: '<b>Sample [Hover to identify Sample and Numbers]</b>',-->
            yaxis: {
                title: '<b>% CHH Calls</b>',
                titlefont: {
                    size: 14,
                    color: '#4d759e',
                }
            },
            margin: {
                l: 50,
                r: 20,
                b: 20,
                t: 0,
                pad: 0,
            },
            legend:{
                x: 0.8,
                y: 0.9,
                orientation: 'h',
            }               
        }
      
		var optionsCpG = {
			displaylogo: false,
			modeBarButtonsToRemove:
				['zoom2d', 
				'pan', 
				'pan2d',
				'resetScale2d',
				'hoverClosestCartesian',
				'hoverCompareCartesian',
				'toggleSpikelines']
			,
			toImageButtonOptions: {
				filename: 'CpG methylation summary',
				width: 1600,  <!-- width: stacksDivPercentage._fullLayout.width, height: stacksDivPercentage._fullLayout.height -->
				height: 200,
				format: 'png'
			}
		};
		var optionsCHG = {
			displaylogo: false,
			modeBarButtonsToRemove:
				['zoom2d', 
				'pan', 
				'pan2d',
				'resetScale2d',
				'hoverClosestCartesian',
				'hoverCompareCartesian',
				'toggleSpikelines']
			,
			toImageButtonOptions: {
				filename: 'CHG methylation summary',
				width: 1600,  <!-- width: stacksDivPercentage._fullLayout.width, height: stacksDivPercentage._fullLayout.height -->
				height: 200,
				format: 'png'
			}
		};
		var optionsCHH = {
			displaylogo: false,
			modeBarButtonsToRemove:
				['zoom2d', 
				'pan', 
				'pan2d',
				'resetScale2d',
				'hoverClosestCartesian',
				'hoverCompareCartesian',
				'toggleSpikelines']
			,
			toImageButtonOptions: {
				filename: 'CHH methylation summary',
				width: 1600,  <!-- width: stacksDivPercentage._fullLayout.width, height: stacksDivPercentage._fullLayout.height -->
				height: 200,
				format: 'png'
			}
		};
	  
        Plotly.newPlot(methylationDiv_CpG, stackedArea(traces_m1), layoutCpG, optionsCpG);
		
		Plotly.newPlot(methylationDiv_CHG, stackedArea(traces_m2), layoutCHG, optionsCHG);
        
		Plotly.newPlot(methylationDiv_CHH, stackedArea(traces_m3), layoutCHH, optionsCHH);
        
            
    </script>
	
	<footer>
		<a style="float:right;" href="https://www.bioinformatics.babraham.ac.uk/">
            {{bioinf_logo_goes_here}}
		</a>

		<p>Analysis produced by <a href="http://www.bioinformatics.babraham.ac.uk/projects/bismark/"><strong>Bismark</strong></a> (version {{bismark_version}}) - a tool to map bisulfite converted sequence reads and determine cytosine methylation states</p>
		
		<p>Report graphs rendered using <a href="https://plot.ly/">plot.ly</a>, design last changed 15 Aug 2018.</p>

	</footer>
</div>
</body>
</html>
HTMLTEMPLATESTRING



### Put in our variables
# replacing the Plot.ly spaceholders with the actual plot.ly code
if ($html_report =~ s/\{\{plotly_goes_here\}\}.*\{\{plotly_goes_here\}\}/$plotly_code/s){
    warn "Plot.ly injection successful!\n" if $verbose;
}
else{
	die "Plot.ly injection not working, won't be able to construct any meaningful HTML reports in this case....\n\n";
}
$html_report =~ s/\{\{bismark_logo_goes_here\}\}/$bismark_logo/;
$html_report =~ s/\{\{bioinf_logo_goes_here\}\}/$bioinf_logo/;
$html_report =~ s/\{\{report_timestamp\}\}/$report_timestamp/g;
$html_report =~ s/\{\{page_title\}\}/$page_title/g;



$html_report =~ s/\{\{num_samples\}\}/$num_samples/g;
# Calculating X Coordinates
my @x_values;
for (1..$num_samples){
	push @x_values, $_;
}
my $x_values = join (",",@x_values);
$html_report =~ s/\{\{x_values_alignment\}\}/$x_values/g;
$html_report =~ s/\{\{x_values_methylation\}\}/$x_values/g;
print "Number of samples: $num_samples\n" if $verbose;
print "X-coords: $x_values\n" if $verbose;

$html_report =~ s/\{\{filenames_replace\}\}/$categories/g;
print "Categories: $categories\n" if $verbose;
$html_report =~ s/\{\{bismark_version\}\}/$bismark_version/g;

####################################################################################
###  ALIGNMENT SECTION
####################################################################################

print "\nALIGNMENT SECTION\n=================\n" if $verbose;
if ($aligned =~ /^,{1,}$/){
	warn "Aligned $aligned contained only commas. Setting it to empty string\n" if $verbose;
	$aligned = '';
}
else{
	warn "Aligned: >$aligned< contained other elements than commas as well\n" if $verbose;	
}	
$html_report =~ s/\{\{aligned_seq\}\}/$aligned/g;
print "Aligned: $aligned\n" if $verbose;

$html_report =~ s/\{\{no_seq\}\}/$no_seq/g;
print "No Seq: $no_seq\n" if $verbose;
$html_report =~ s/\{\{not_aligned\}\}/$not_aligned/g;
print "Not Aligned: $not_aligned\n" if $verbose;
$html_report =~ s/\{\{ambig_aligned\}\}/$ambig_aligned/g;
print "Ambiguous Aligned: $ambig_aligned\n" if $verbose;

### DEDUPLICATED ALIGNMENTS
if ($dup_alignments =~ /^,{1,}$/){
	warn "Duplicated Alignments: >$dup_alignments< contained only commas. Deleting the Deduplicated Unique alignment section from the template altogher\n" if $verbose;	
	$html_report =~ s/\{\{deduplicated_unique_reads_section\}\}.*\{\{deduplicated_unique_reads_section\}\}//s; # treating as single line
	$html_report =~ s/\{\{duplicated_reads_section\}\}.*\{\{duplicated_reads_section\}\}//s; # treating as single line
	$html_report =~ s/\{\{raw_aligned_reads_section\}\}//g;
	$dup_alignments = '';
}
else{
	warn "Duplicated Alignments: >$dup_alignments< contained other elements than commas, deleting the Raw Alignment Section\n" if $verbose;
	$html_report =~ s/\{\{raw_aligned_reads_section\}\}.*\{\{raw_aligned_reads_section\}\}//s; # treating as single line
	$html_report =~ s/\{\{deduplicated_unique_reads_section\}\}//g;
	$html_report =~ s/\{\{duplicated_reads_section\}\}//g;
}	
$html_report =~ s/\{\{dup_alignments\}\}/$dup_alignments/g;
print "Duplicated alignments: $dup_alignments\n" if $verbose;

### UNIQUE DEDUPLICATED ALIGNMENTS
if ($unique_alignments =~ /^,{1,}$/){
	warn "Unique alignments: >$unique_alignments< contained only commas. Setting it to empty string\n" if $verbose;	
	$unique_alignments = '';	
}
else{#
	warn ">$unique_alignments< contained other elements than  commas as well\n" if $verbose;	
}	
$html_report =~ s/\{\{unique_alignments\}\}/$unique_alignments/g;
print "Unique Alignments: $unique_alignments\n" if $verbose;


### Calculating percentages
	
my @perc_aligned;
if ($aligned){
	warn "Found raw, undeduplicated unique aligments. Using those...\n" if $verbose;
	print "Aligned:\t",join (" ~~ ",@aligned_arr),"\n" if $verbose;
}
else{
	print "Unique Deduplicated Aligned:\t",join (" ~~ ",@unique_alignments_arr),"\n" if $verbose;
	print "Duplicated Aligned:\t",join (" ~~ ",@dup_alignments_arr),"\n" if $verbose;
}
if ($unique_alignments){
	warn "Found deduplicated unique aligments. Using those...\n" if $verbose;
}	
print "Not Aligned:\t",join (" ~~ ",@not_aligned_arr),"\n" if $verbose;
print "No Sequence:\t",join (" ~~ ",@no_seq_arr),"\n" if $verbose;
print "Ambiguous:\t",  join (" ~~ ",@ambig_aligned_arr),"\n" if $verbose;

my @p_aligned;
my @p_deduplicated_unique_alignments;
my @p_duplicated_alignments;
my @p_not_aligned;
my @p_no_seq;
my @p_ambig_aligned;

### Calculating percentages for the Alignment graph
foreach my $index (0..$#aligned_arr){
	my $total;
	if ($aligned){ # raw alignments, e.g. RRBS

        if ($aligned_arr[$index] eq ''){
            die "\n\nIt looks like there is a mix of samples, e.g. RRBS as well as WGBS, in this folder. Please consider running bismark2summary only on samples of the same data type,\nor specify the input files manually (--help for more information). Extiting...\n\n";
        }

		$total = $aligned_arr[$index] + $no_seq_arr[$index] + $not_aligned_arr[$index] +$ambig_aligned_arr[$index];
        # warn "Aligned: >$aligned_arr[$index]<\n"; sleep(1);
        # warn "No Seq: $no_seq_arr[$index]\n"; sleep(1);
        # warn "Not Aligned: $not_aligned_arr[$index]\n"; sleep(1);
        # warn "Ambig aligned: $ambig_aligned_arr[$index]\n"; sleep(1);
	}
	else{ # including de-duplicated reads, $aligned was set to '' in the section above
		$total = $unique_alignments_arr[$index] + $dup_alignments_arr[$index] + $no_seq_arr[$index] + $not_aligned_arr[$index] +$ambig_aligned_arr[$index];
	}	

	# warn "Aligned: $perc_aligned[$index]\nNo Seq: $perc_no_seq[$index]\nNot Aligned: $perc_not_aligned[$index]\nAmbig: $perc_ambig_aligned[$index]\nTotal: $total\n~~~~~~~~\n\n";
 
	my ($p_al,$p_dedup_uniq,$p_dup);
	if ($aligned){
		$p_al          = sprintf("%.2f", $aligned_arr[$index] / $total * 100);
	}
	else{
		$p_dedup_uniq  = sprintf("%.2f", $unique_alignments_arr[$index] / $total * 100);
		$p_dup         = sprintf("%.2f", $dup_alignments_arr[$index] / $total * 100);
	}

    my $p_no_seq      = sprintf("%.2f", $no_seq_arr[$index] / $total * 100);
    my $p_unal        = sprintf("%.2f", $not_aligned_arr[$index] / $total * 100);
    my $p_ambig       = sprintf("%.2f", $ambig_aligned_arr[$index] / $total * 100);

    if ($verbose){
		if ($aligned){
			print "Aligned: $perc_aligned[$index] ($p_al%)\n";
		}
		else{
			print "Unique Aligned: $unique_alignments_arr[$index] ($p_dedup_uniq%)\n";
			print "Aligned: $dup_alignments_arr[$index] ($p_dup%)\n";
		}	
        print "No Seq:  $no_seq_arr[$index] ($p_no_seq%)\n";
        print "Not Aligned: $not_aligned_arr[$index] ($p_unal%)\n";
        print "Ambiguous Aligned: $ambig_aligned_arr[$index] ($p_ambig%)\n";
        print "Total: $total\n\n";
    }  

    if ($aligned){
		push @p_aligned,   $p_al;
	}
	else{
		push @p_deduplicated_unique_alignments, $p_dedup_uniq;
		push @p_duplicated_alignments,          $p_dup;
	}
	push @p_not_aligned,   $p_unal;
    push @p_no_seq,        $p_no_seq;
    push @p_ambig_aligned, $p_ambig;
}


### Replacing in the HTML template
print "Using the following values to replace percentage spaceholders:\n" if $verbose;
if ($aligned){
	print "Aligned:\t",       join ("\t", @p_aligned),"\n" if $verbose;
}
else{
	print "Unique Aligned:\t",join ("\t", @p_deduplicated_unique_alignments),"\n" if $verbose;
	print "Duplicated:\t",    join ("\t", @p_duplicated_alignments),"\n" if $verbose;
}
print "Unaligned:\t",     join ("\t", @p_not_aligned),"\n" if $verbose;
print "No Seq:\t\t",      join ("\t", @p_no_seq),"\n" if $verbose;
print "Ambig Aligned:\t", join ("\t", @p_ambig_aligned),"\n" if $verbose;

my ($p_aligned_replace, $p_unique_dedup_replace, $p_dup_replace);
if ($aligned){
	$p_aligned_replace      = join (",", @p_aligned);
}
else{
	$p_unique_dedup_replace = join (",", @p_deduplicated_unique_alignments);
	$p_dup_replace          = join (",", @p_duplicated_alignments);
}
my $p_unal_replace          = join (",", @p_not_aligned);
my $p_no_seq_replace        = join (",", @p_no_seq);
my $p_ambig_replace         = join (",", @p_ambig_aligned);

if ($aligned){
	warn "$p_aligned_replace\n$p_unal_replace\n$p_no_seq_replace\n$p_ambig_replace\n\n" if $verbose;
}
else{

	warn "$p_unique_dedup_replace\n$p_dup_replace\n$p_unal_replace\n$p_no_seq_replace\n$p_ambig_replace\n\n" if $verbose;
}

if ($aligned){
	warn "Only raw alignments. Deleting the Deduplicated Unique Alignment and duplicated sections (Percentage) from the template altogher\n" if $verbose;
	$html_report =~ s/\{\{deduplicated_unique_reads_percentage_section\}\}.*\{\{deduplicated_unique_reads_percentage_section\}\}//s; # treating as single line
	$html_report =~ s/\{\{duplicated_reads_percentage_section\}\}.*\{\{duplicated_reads_percentage_section\}\}//s; # treating as single line
	$html_report =~ s/\{\{raw_unique_reads_percentage_section\}\}//g;
}
else{
	warn "Deleting the Raw Alignment Section\n\n" if $verbose;
	$html_report =~ s/\{\{raw_unique_reads_percentage_section\}\}.*\{\{raw_unique_reads_percentage_section\}\}//s; # treating as single line
	$html_report =~ s/\{\{duplicated_reads_percentage_section\}\}//g;
	$html_report =~ s/\{\{deduplicated_unique_reads_percentage_section\}\}//g;
}

if ($aligned){
	$html_report =~ s/\{\{p_aligned_replace\}\}/$p_aligned_replace/;
}
else{
	$html_report =~ s/\{\{p_deduplicated_unique_alignments\}\}/$p_unique_dedup_replace/;
	$html_report =~ s/\{\{p_duplicated_alignments\}\}/$p_dup_replace/;
}
$html_report =~ s/\{\{p_no_seq_replace\}\}/$p_no_seq_replace/;
$html_report =~ s/\{\{p_unal_replace\}\}/$p_unal_replace/;
$html_report =~ s/\{\{p_ambig_replace\}\}/$p_ambig_replace/;


#################################################################
### METHYLATION CONTEXT SECTION
#################################################################

print "METHYLATION CONTEXT SECTION\n===========================\n" if $verbose;
$html_report =~ s/\{\{meth_cpg_string\}\}/$meth_cpg_string/g;
print "  Meth CpG:\t$meth_cpg_string\n" if $verbose;
$html_report =~ s/\{\{unmeth_cpg_string\}\}/$unmeth_cpg_string/g;
print "Unmeth CpG:\t$unmeth_cpg_string\n" if $verbose;
$html_report =~ s/\{\{meth_chg_string\}\}/$meth_chg_string/g;
print "  Meth CHG:\t$meth_chg_string\n" if $verbose;
$html_report =~ s/\{\{unmeth_chg_string\}\}/$unmeth_chg_string/g;
print "Unmeth CHG:\t$unmeth_chg_string\n" if $verbose;
$html_report =~ s/\{\{meth_chh_string\}\}/$meth_chh_string/g;
print "  Meth CHH:\t$meth_chh_string\n" if $verbose;
$html_report =~ s/\{\{unmeth_chh_string\}\}/$unmeth_chh_string/g;
print "Unmeth CHH:\t$unmeth_chh_string\n\n" if $verbose;


my @p_CpG_m;
my @p_CpG_u;
my @p_CHG_m;
my @p_CHG_u;
my @p_CHH_m;
my @p_CHH_u;

### Calculating percentages for the Methylation Conntext graph
foreach my $index (0..$#meth_cpg_string_arr){

    my $total_CpG = $meth_cpg_string_arr[$index] + $unmeth_cpg_string_arr[$index];
    my $total_CHG = $meth_chg_string_arr[$index] + $unmeth_chg_string_arr[$index];  
    my $total_CHH = $meth_chh_string_arr[$index] + $unmeth_chh_string_arr[$index];

    # warn "Trying to work with these numbers:\nCpG: $meth_cpg_string_arr[$index]\nCpG: $meth_chg_string_arr[$index]\nCHH: $meth_chh_string_arr[$index]\n";
    # warn "Total: CpG: $total_CpG\nCHG: $total_CHG\nCHH: $total_CHH\n\n";
    my $p_CpG_meth;
	my $p_CpG_unmeth;
	if ($total_CpG == 0){ # if this context was not covered at all we assign '0' as the value for percentages. This will get plotted in a funky way but does not break the code
		$p_CpG_meth = 'NA';
		$p_CpG_unmeth  = 'NA';
	}
	else{
		$p_CpG_meth = sprintf("%.2f",$meth_cpg_string_arr[$index] / $total_CpG * 100);
		$p_CpG_unmeth = 100 - $p_CpG_meth;
	}
	
    my $p_CHG_meth;
	my $p_CHG_unmeth;
	if ($total_CHG == 0){ # if this context was not covered at all we assign '0' as the value for percentages. This will get plotted in a funky way but does not break the code
		$p_CHG_meth = '0';
		$p_CHG_unmeth  = '0';
	}
	else{
		$p_CHG_meth = sprintf("%.2f",$meth_chg_string_arr[$index] / $total_CHG * 100);
		$p_CHG_unmeth = 100 - $p_CHG_meth;
	}
 

	my $p_CHH_meth;
	my $p_CHH_unmeth;
	if ($total_CHG == 0){ # if this context was not covered at all we assign '0' as the value for percentages. This will get plotted in a funky way but does not break the code
		$p_CHH_meth = '0';
		$p_CHH_unmeth  = '0';
	}
	else{
		$p_CHH_meth = sprintf("%.2f",$meth_chh_string_arr[$index] / $total_CHH * 100);
		$p_CHH_unmeth = 100 - $p_CHH_meth;   
	}
	
    if ($verbose){
        print "Meth CpG:   $meth_cpg_string_arr[$index] ($p_CpG_meth%)\n";
        print "Unmeth CpG: $unmeth_cpg_string_arr[$index] ($p_CpG_unmeth%)\n";
        
        print "Meth CHG:   $meth_chg_string_arr[$index] ($p_CHG_meth%)\n";
        print "Unmeth CHG: $unmeth_chg_string_arr[$index] ($p_CHG_unmeth%)\n";

        print "Meth CHH:   $meth_chh_string_arr[$index] ($p_CHH_meth%)\n";
        print "Unmeth CHH: $unmeth_chh_string_arr[$index] ($p_CHH_unmeth%)\n";

        print "Total CpG: $total_CpG\n";
        print "Total CHG: $total_CHG\n";
        print "Total CHH: $total_CHH\n\n";

    }  
    push @p_CpG_m, $p_CpG_meth;
    push @p_CpG_u, $p_CpG_unmeth;
    push @p_CHG_m, $p_CHG_meth;
    push @p_CHG_u, $p_CHG_unmeth;
    push @p_CHH_m, $p_CHH_meth;
    push @p_CHH_u, $p_CHH_unmeth;
}

### Replacing in the HTML template

my $p_CpG_m_replace = join (",", @p_CpG_m);
my $p_CpG_u_replace = join (",", @p_CpG_u);
my $p_CHG_m_replace = join (",", @p_CHG_m);
my $p_CHG_u_replace = join (",", @p_CHG_u);
my $p_CHH_m_replace = join (",", @p_CHH_m);
my $p_CHH_u_replace = join (",", @p_CHH_u);


warn "$p_CpG_m_replace\n$p_CpG_u_replace\n$p_CHG_m_replace\n$p_CHG_u_replace\n$p_CHH_m_replace\n$p_CHH_u_replace\n\n" if $verbose;

$html_report =~ s/\{\{p_CpG_m_replace\}\}/$p_CpG_m_replace/;
$html_report =~ s/\{\{p_CpG_u_replace\}\}/$p_CpG_u_replace/;
$html_report =~ s/\{\{p_CHG_m_replace\}\}/$p_CHG_m_replace/;
$html_report =~ s/\{\{p_CHG_u_replace\}\}/$p_CHG_u_replace/;
$html_report =~ s/\{\{p_CHH_m_replace\}\}/$p_CHH_m_replace/;
$html_report =~ s/\{\{p_CHH_u_replace\}\}/$p_CHH_u_replace/;



# Write the HTML report to disk
my $html_fn = "${report_basename}.html";
open(SUMMARY_HTML, ">", $html_fn) or die("Can't open $html_fn: $!\n");
print SUMMARY_HTML $html_report;
close(SUMMARY_HTML) or warn "Failed to close fh: $!\n";

warn("\nWrote Bismark project summary to >> $html_fn <<\n\n");
